import { packageRead } from "@/module/Socket";

export function Str2CharArray(Str: string) {
    var arr = [];
    for (var i = 0, j = Str.length; i < j; ++i)
        arr.push(Str.charCodeAt(i))
        
    return arr
}

export function StreamRead(msg: any): any{
    let responseMsg: any = ""
    let responseOperator = null
    const reader = new FileReader();
    if(msg.data instanceof Blob) {
      reader.readAsText(msg.data, "UTF-8")
      reader.onload = () => {
        //获取包内容，0-15是包头
        responseMsg = reader.result?.slice(16)
        //11是获取WebSocket返回包的类型
        responseOperator = (reader.result as string).charCodeAt(11)
        //心跳回复包没有数据包体
        try {
          responseMsg = JSON.parse(responseMsg)
        } catch (e) {
          responseMsg = ""
        }    
        //来回乱调，不知道其他办法了
        packageRead(responseMsg, responseOperator)
      }
    }

}

export function stringLengthB(str: string) {    
  var len = 0    
  for (var i=0; i<str.length; i++) {    
      if (str.charCodeAt(i)>127 || str.charCodeAt(i)==94) {    
           len += 2    
       } else {    
           len ++    
       }    
   }    
  return len;    
}    

export function stringSubstrB(str: string, start: number = 0, end?: number) {    
  if(!end) return str
  let n = 0;
  var i = 0;
  for (; i<str.length; i++) {    
      if (str.charCodeAt(i)>127 || str.charCodeAt(i)==94) { 
          if(n+2 >= end) break   
          n += 2    
      } else {    
          if(n+1 >= end) break   
          n ++    
      }
         
   }  
  return str.substring(start, i)
}    

export function convert(a: any) {
  const b = []
  for (const i in a)
    for (const j in a[i])
      b[a[i][j]] = i
  return b
}

export function isNum(string: any) {
  const _string = parseInt(string)
  return _string == string ? _string : false
}